package com.fancon.android.gardenjokesx.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import android.app.Activity;

import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.multithread.RequestUI;

public class DownloadImageTask extends RequestUI{
	public interface IExcuteUi{
		public void preExecute();
		public void execute();
		public void executeUI(String realPath);
	}
	private IExcuteUi ie = null;
	
	private Boolean isExist = false;
	private String realPath ="";
	private String url;
	public DownloadImageTask(Object key, Activity activity, final String url) {
		super(key, activity);
		this.url = url;
		// TODO Auto-generated constructor stub
		if(ie != null){
			ie.preExecute();
		}
		//check image exist on sdcard
		File cacheDir = StorageUtils.getIndividualCacheDirectory(activity);
		File realFile = new File(cacheDir, String.valueOf(url.hashCode()));
		realPath = realFile.getAbsolutePath();
		if(realFile.exists()){
			isExist = true;
		}
	}

	@Override
	public void execute() throws Exception {
		// TODO Auto-generated method stub
		if(ie != null){
			ie.execute();
		}
		if(!isExist){
			URL urlx = new URL (url);
			InputStream input = urlx.openStream();
			try {
			    OutputStream output = new FileOutputStream (realPath);
			    try {
			        byte[] buffer = new byte[512];
			        int bytesRead = 0;
			        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
			            output.write(buffer, 0, bytesRead);
			        }
			    } finally {
			        output.close();
			    }
			} finally {
			    input.close();
			}

		}
		isExist = true;
	}

	@Override
	public void executeUI(Exception ex) {
		// TODO Auto-generated method stub
		if(ie != null){
			ie.executeUI(realPath);
		}
		if(isExist){
			
		}
	}

	public IExcuteUi getIe() {
		return ie;
	}

	public void setIe(IExcuteUi ie) {
		this.ie = ie;
	}

}
